package com.lemo.dao;


import com.lemo.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate dao;


    @Override
    public User get(Serializable id) {
        List<User> query = dao.query("select * from user where id = ?", new Object[]{id}, new BeanPropertyRowMapper<User>(User.class));
        if (!CollectionUtils.isEmpty(query)) {
            return query.get(0);
        }
        return null;
    }

    @Override
    public int update(User record) throws Exception {
        return dao.update("update user set password = ?,tel = ?,username=?  where id =?",
                new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement ps) throws SQLException {
                        ps.setString(1, record.getPassword());
                        ps.setString(2, record.getTel());
                        ps.setString(3, record.getUsername());
                        ps.setLong(4, record.getId());
                    }
                });
    }

    @Override
    public int add(User record) throws Exception {
        return dao.update(" insert into user (username, money) values(?,?)",
                new Object[]{record.getUsername(), record.getMoney()});
    }

    @Override
    public int del(Serializable id) {
        return dao.update("delete from user where id =" + id);
    }
}
